// 登录组件
<template>
  <div class="body">
    <el-form autocomplete="on" :model="loginForm" ref="loginForm">
      <el-form-item prop="username" class="username-item">
        <el-input
          type="text"
          placeholder="请输入账号"
          autocomplete="on"
          v-model="loginForm.username"
          name="username"
        >
          <template slot="prepend">账号</template>
        </el-input>
      </el-form-item>
      <!-- 账号输入框 -->

      <el-form-item prop="password" class="password-item">
        <el-input
          type="password"
          placeholder="请输入密码"
           v-model="loginForm.password"
          autocomplete="on"
        >
          <template slot="prepend">密码</template>
        </el-input>
      </el-form-item>
      <!-- 密码输入框 -->

      <el-form-item prop="password" v-if="logidentify">
        <el-row>
          <el-col :span="12">
            <div @click="refreshCode">
              <validation :identifyCode="identifyCode"></validation>
            </div>
          </el-col>
          <el-col :span="12">
            <el-input
              type="text"
              class="code"
              v-model="code"
              placeholder="验证码"
              @keyup.enter.native="handleLogin"
            >
            </el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <!-- 验证码 -->

      <el-row type="flex" class="bottom-hub" justify="space-between">
        <el-col :span="6">
          <el-checkbox v-model="pwdSave">保存密码</el-checkbox>
        </el-col>
        <el-col :span="6">
          <el-button class="SubBut" type="primary" plain @click="handleLogin">登录</el-button>
        </el-col>
      </el-row>
      <!-- 保存密码选项 -->
      
    </el-form>
  </div>
</template>

<script>
import validation from "./validation";
import {mapState} from 'vuex';

export default {
  components: {
    validation,
  },
  data() {
    return {
      identifyCodes: "1234567890",
      identifyCode: "",
      code: "", // text框输入的验证码
      logcnt: 0,
      logidentify: true,
      message: "",
      loginForm: {
        username: "",
        password: "",
        ipLocation: ""
      },
      pwdSave: false,
      uid: 0
      // pwdicon: true
    };
  },
  methods: {
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    },

    refreshCode() {
      this.identifyCode = "";
      this.makeCode(this.identifyCodes, 4);
    },

    makeCode(o, len) {
      for (let i = 0; i < len; i++) {
        this.identifyCode += this.identifyCodes[
          this.randomNum(0, this.identifyCodes.length)
        ];
      }
      // console.log(this.identifyCode);
    },
    loginerror(errormessage) {
      this.refreshCode();
      this.$message.error(errormessage);
      this.code = "";
    },
    // 错误提示
    handleLogin() {
      if (this.loginForm.username === "") {
        this.loginerror("请输入账号");
        return false;
      }
      if (this.loginForm.password === "") {
        this.loginerror("请输入密码");
        return false;
      }
      if (this.code != this.identifyCode) {
        if (this.code === "") this.loginerror("请输入验证码");
        else this.loginerror("验证码错误");
        return false;
      }
      var reg = /\s+/g; // 正则表达式，全局搜索空白字符
      if (
        this.loginForm.username.search(reg) != -1 ||
        this.loginForm.password.search(reg) != -1
      ) {
        this.loginerror("请输入正确的账号或密码");
        return false;
      }
      if (this.pwdSave) {
        this.setCookie(this.loginForm.username, this.loginForm.password, 7);
      } else this.setCookie(this.loginForm.username, "", 7);
      // console.log("agree");
      // console.log(this.loginForm.ipLocation)
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.$store
            .dispatch("Login", this.loginForm)
            .then((response) => {
              let code = response.data.code;
              // console.log(code)
              if (code === 200) {
                this.$router.push({name: "main"}); // 成功后跳转至主页面
                this.$store.commit("Reguid",response.data.data)
                this.$store.commit("Regtoken",response.data.message)
              }
              else if(code === 201){
                this.$router.push({name: "welcomefirst"}); // 首次登录进入首次登录页面
                this.$store.commit("Reguid",response.data.data)
                this.$store.commit("Regtoken",response.data.message)
              } 
              else {
                this.loginerror("账号或密码错误");
                return false;
              }
            })
            .catch(() => {});
        } else {
          // eslint-disable-next-line no-console
          this.loginerror("参数验证不合法！");
          return false;
        }
      });
    },
    setCookie(name, pwd, exdays) {
      var exdate = new Date(); //获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
      //字符串拼接cookie
      document.cookie =
        "userName" + "=" + name + ";path=/;expires=" + exdate.toGMTString();
      document.cookie =
        "userPwd" + "=" + pwd + ";path=/;expires=" + exdate.toGMTString();
      // console.log(document.cookie);
    }, // 设置账号密码cookie
    getCookie: function () {
      if (document.cookie.length <= 0) return;
      // console.log(document.cookie);
      var arr = document.cookie.split("; ");
      // console.log(arr);
      for (var i = 0; i < arr.length; i++) {
        var arr2 = arr[i].split("=");
        if (arr2[0] === "userName") this.loginForm.username = arr2[1];
        else if (arr2[0] === "userPwd") {
          this.loginForm.password = arr2[1];
          this.pwdSave = true;
        }
      }
    },
  },
  computed:{
    ...mapState({
      usertoken: state => state.session.token,
      useruid: state => state.session.uid
    })
  },
  mounted() {
    this.refreshCode();
    this.getCookie();
    this.loginForm.ipLocation=returnCitySN["cip"].toString(); // eslint-disable-line no-undef
  }
};
</script>

<style scoped>
@import "../style/login.css";
</style>
